#!/usr/bin/python


#######################

class basicWriter:

	def __init__(self):
		self.functions = []
		self.currentFunction = -1
		
	def addFunction(self, name):
		self.currentFunction = name
		newNode = Function(name)
		self.functions.append(newNode)

	def addValue(self, value, functionName = ""):
		if (functionName == ""):
			functionName = self.currentFunction
		if (functionName == -1):
			print ('Sorry, there are no functions')
			return
		for function in self.functions:
			if (function.name == functionName):
				selection = function
				break
		if ( not selection):
			print ('Sorry, function %s not found') % functionName
			return
		selection.addValue(value)

	def addSubset(self, name, functionName = ""):
		if (functionName == ""):
	 		functionName = self.currentFunction
		if (functionName == -1):
			print ('Sorry, there are no functions')
			return
		for function in self.functions:
			if (function.name == functionName):
				selection = function
				break
		if ( not selection):
			print ('Sorry, function %s not found') % functionName
			return
		selection.addSubset(name)

	def getSubsets(self, functionName = ""):
		if (functionName == ""):
	 		functionName = self.currentFunction
		if (functionName == -1):
			print ('Sorry, there are no functions')
			return
		for function in self.functions:
			if (function.name == functionName):
				selection = function
				break
		if ( not selection):
			print ('Sorry, function %s not found') % functionName
			return
		return selection.getSubsets()	

	def writeXML(self):
		output = ""
		for each in self.functions:
			output += each.name + "{"  
			output += each.printProperties()
			output += "}"
		return output

class Function:
#######################################
#  Each Function has at least one subset, 
#  and each subset is a pair of (a name, a list of values).
######################################
	
	def __init__(self, name):
		self.name = name
		self.subsets = []		

	def addValue(self, value):
		self.subsets[-1][1].append(value)

	def addSubset(self, name):
		self.subsets.append((name, []))

	def getSubsets(self):
		return self.subsets

	def getValues(self, subsetName=""):
		if subsetName == "":
			return self.subsets[-1][1]
		else:
			for each in self.subsets:
				if each[0] == subsetName:
					return each[1]
		return []			

	def printProperties(self):
		output = ""
		for each in self.subsets:
			output += each[0] + ":"
			for prop in each[1:]:
				output += str(prop) + ","
			output = output[0:-1]
			output += ";"
		return output		
				
							


